<template>
  <div>
    <r-search
      ref="search"
      :searchData="searchData"
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :inline="true"
    />

    <r-table
      :isPagination="true"
      :isHandle="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="pagination"
      :loading="tableLoading"
      :tableHandles="tableHandles"
      :isSelection="false"
      @refresh="page()"
    />

    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="130px"
      dialogWidth="550px"
      :isHandle="true"
    />
    <el-dialog title="Add Order" :visible.sync="isPromoter" width="35%">
      <el-form
        :model="operateData"
        :status-icon="true"
        :rules="operateRules"
        ref="operateData"
        label-width="100px"
        class="renewalData"
      >
        <el-form-item label="Order ID" prop="id" v-if="false">
          <el-input v-model="operateData.id" :disabled="true" />
        </el-form-item>
        <el-form-item label="Battery Number" prop="batteryNo">
          <el-input v-model="operateData.batteryNo" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isPromoter = false">Cancel</el-button>
        <el-button type="primary" @click="PromoterFn('operateData')"
          >Confirm</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      isPromoter: false,
      operateData: {
        id: "",
        batteryNo: "" //Battery Number
      },
      operateRules: {
        id: [{ required: true, message: "Please Enter", trigger: "blur" }],
        batteryNo: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ]
      },
      searchData: {
        orderNo: "",
        deviceNo: "",
        phone: "",
        userName: "",
        beginTime: "",
        endTime: "",
        newBatteryNo: ""
      },
      searchForm: [
        {
          type: "input",
          placeholder: "Order Nnumber",
          prop: "orderNo",
          width: 240
        },
        {
          type: "input",
          placeholder: "Device Number",
          prop: "deviceNo",
          width: 240
        },
        {
          type: "date",
          placeholder: "Start Date",
          prop: "beginTime",
          width: 240,
          change: val => {
            this.searchData.beginTime = val;
          }
        },
        {
          type: "date",
          placeholder: "End Date",
          prop: "endTime",
          width: 240,
          change: val => {
            this.searchData.endTime = val;
          }
        },
        { type: "input", placeholder: "Phone", prop: "phone", width: 200 },
        { type: "input", placeholder: "User", prop: "userName", width: 200 },
        {
          type: "input",
          placeholder: "New Battery Number",
          prop: "newBatteryNo",
          width: 280
        }
      ],
      searchHandle: [
        {
          type: "primary",
          label: "Search",
          plain: true,
          handle: e => {
            this.zeroFn();
            this.getData();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              orderNo: "",
              deviceNo: "",
              phone: "",
              userName: "",
              beginTime: "",
              endTime: "",
              newBatteryNo: ""
            };
            this.zeroFn();
            this.getData();
          }
        }
      ],
      tableLoading: false,
      tableData: [{}],
      tableCols: [
        { label: "Order Nnumber", prop: "orderNo" },
        // { label: "订单Type", prop: "nickName",  },
        { label: "Package Information", prop: "mealName" },
        { label: "New Battery Number", prop: "newBatteryNo" },
        { label: "Old Battery Number", prop: "oldBatteryNo" },
        { label: "Device Number", prop: "deviceNo" },
        { label: "User", prop: "userName" },
        { label: "Phone", prop: "phone" },
        // { label: "订单Money", prop: "isVip_des",  },
        // { label: "PaymentMoney", prop: "isVip_des",  },
        {
          label: "Order Status",
          prop: "status",
          // type: 'html',
          // html: (row) => {
          //   let html = '<p>' +
          //     (row.status == 0 ? "进行中" :
          //       row.status == 1 ? "Completed" :
          //         row.status == 2 ? "Overdue" :
          //           row.status == 3 ? "订单Already Cancel" : "--")
          //     + '</p>'
          //   return html
          // },
          itemClass: e => (e.status == 3 ? "danger" : ""),
          formatter: e =>
            e.status == 0
              ? "Underway"
              : e.status == 1
              ? "Completed"
              : e.status == 2
              ? "Overdue"
              : e.status == 3
              ? "Cancel Order"
              : "--"
        },
        {
          label: "BatteryStatus",
          prop: "btStatus",

          itemClass: e => (e.btStatus == 1 ? "success" : ""),
          formatter: e =>
            e.btStatus == 0
              ? "Lease"
              : e.btStatus == 1
              ? "Already Return"
              : e.btStatus == 2
              ? "Not Returned"
              : e.btStatus == 3
              ? "Illegality Battery"
              : e.btStatus == 4
              ? "Battery Mismatching"
              : "--"
        },
        {
          label: "Business Type",
          prop: "openType",
          formatter: e =>
            e.openType == 1
              ? "Rent Battery"
              : e.openType == 2
              ? "Battery Swap"
              : e.openType == 3
              ? "Keeper Opens Door"
              : "--"
        },
        {
          label: "Cabinet Opening Result",
          prop: "openResult",
          itemClass: e => (e.openResult == 0 ? "danger" : "success"),
          formatter: e =>
            e.openResult == 0 ? "Failure" : e.openResult == 1 ? "Success" : "--"
        },
        { label: "Start Time", prop: "ctime" },
        { label: "Completion Time", prop: "ftime" },

        {
          label: "Operations",
          type: "button",
          width: 260,
          btnList: [
            {
              label: "End Order",
              type: "primary",
              plain: true,
              size: "small",
              handle: row => {
                this.$confirm("Confirm End Order?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    const res = await this.apis.orderExchange_endOrder({
                      id: row.id
                    });
                    this.$message({
                      type: "success",
                      message: "Operations Success!"
                    });
                  })
                  .catch(() => {});
              },
              isShow: row => {
                if (row.status == 3) {
                  return false;
                } else {
                  return true;
                }
              }
            },
            // {
            //   label: 'Order Details',
            //   type: 'text',
            //   handle: (row) =>{}
            // },
            {
              label: "Replace Battery",
              type: "primary",
              plain: true,
              size: "small",
              style: { "margin-bottom": "5px" },
              handle: row => {
                this.formData.id = row.id;
                this.elFormVisible("Replace Battery");
              },
              isShow: row => {
                if (row.status == 3) {
                  return false;
                } else {
                  return true;
                }
              }
            },
            {
              label: "Return",
              type: "danger",
              plain: true,
              size: "small",
              isShow: row => {
                if (row.btStatus == 2 && row.status !== 3) {
                  return true;
                } else {
                  return false;
                }
              },
              handle: row => {
                this.$confirm("Confirm Return?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    const res = await this.apis.orderExchange_giveBack({
                      id: row.id
                    });
                    this.$message({
                      type: "success",
                      message: "Operations Success!"
                    });
                    this.getData();
                  })
                  .catch(() => {});
              }
            },
            {
              label: "Add Order",
              type: "success",
              plain: true,
              size: "small",
              handle: row => {
                this.operateData.id = row.id;
                this.isPromoter = true;
              },
              isShow: row => {
                if (row.status == 3) {
                  return true;
                } else {
                  return false;
                }
              }
            }
          ]
        }
      ],
      tableHandles: [
        {
          label: "Battery Swap Orders Export",
          type: "primary",
          icon: "el-icon-download",
          // titles:
          //   "可以根据Order Nnumber、Device Number、Phone、Start Time、End Time筛选出订单再Export，也可以不选，直接ExportWhole订单",
          plain: true,
          loading: false,
          handle: async e => {
            const res = await this.apis.orderExchangeExport(this.searchData);
            // console.log(333, this.searchData, res.msg);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.code == 200 ? "success" : "error"
            });
            location.href = process.env.VUE_APP_URL + res.msg;
          }
        }
      ],
      pagination: { limit: 10, offset: 1, total: 0 },

      formData: {
        id: "",
        batteryNo: ""
      },
      formCols: [
        {
          type: "input",
          label: "Replace Battery",
          placeholder: "Please Enter Replace Battery Number",
          width: 350,
          prop: "batteryNo",
          rmblock: true,
          remark: ""
        }
      ],
      formRules: {
        batteryNo: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => {
            this.$refs.elForm.$refs.ruleForm.validate(async valid => {
              if (valid) {
                const res = await this.apis.orderExchange_replace(
                  this.formData
                );
                this.$message({
                  message: "Operations Success！",
                  type: "success"
                });
                this.getData();
                this.elFormVisible();
              }
            });
          }
        }
      ]
    };
  },

  watch: {
    isPromoter: {
      handler(newValue) {
        if (!newValue) {
          this.operateData.batteryNo = "";
        }
      },
      deep: true // 深度监听
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    async PromoterFn(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.apis.orderExchangeCreateOrder(this.operateData);
          console.log(444, this.operateData, res);
          this.$message({
            message: res.msg,
            type: res.code == 200 ? "success" : "error"
          });
          this.getData();
          this.isPromoter = false;
        }
      });
    },
    zeroFn() {
      this.pagination.limit = 10;
      this.pagination.offset = 1;
      this.pagination.total = 0;
    },
    userDetailsCall() {
      this.userDetailsData.show = false;
    },
    async usersys_updata(row) {
      var res = await this.apis.usersys_updata({
        id: row.id,
        state: row.state == 34 ? 35 : 34
      });
      this.getData();
    },
    async getData() {
      var res = await this.apis.orderExchange_list({
        orderNo: this.searchData.orderNo,
        deviceNo: this.searchData.deviceNo,
        phone: this.searchData.phone,
        userName: this.searchData.userName,
        newBatteryNo: this.searchData.newBatteryNo,
        beginTime: this.searchData.beginTime,
        endTime: this.searchData.endTime,
        pageNum: this.pagination.offset,
        pageSize: this.pagination.limit
      });
      // console.log(res);
      var list = res.rows || [];

      this.tableData = list;
      this.pagination.total = res.total;
    },
    page() {
      this.getData();
    }
  }
};
</script>

<style scoped lang="scss"></style>
